import base64
import json
import os
from time import time
from checkin import CheckIn
import requests
from bs4 import BeautifulSoup

headers = {
    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 "
                  "Safari/537.36",
    "cookie": "",
    "x-csrf-token": "",
    "referer": "https://www.luogu.com.cn/auth/login",
}


class Luogu(CheckIn):
    name = "洛谷"

    def __init__(self, check_item) -> None:
        self.check_item = check_item

    @staticmethod
    def get_csrf() -> (str, str):
        global headers
        _res = requests.get("https://www.luogu.com.cn/", headers=headers)
        _cookie = _res.cookies.get_dict()
        _cookie = '; '.join([f'{i}={_cookie[i]}' for i in _cookie])
        _csrf = BeautifulSoup(_res.text, 'html.parser').find(
            'meta', {'name': 'csrf-token'}).get('content')
        return _cookie, _csrf

    @staticmethod
    def get_captcha() -> bytes:
        global headers
        _params = {"_t": str(time() * 1e3)}
        _res = requests.get("https://www.luogu.com.cn/api/verify/captcha",
                            params=_params,
                            headers=headers)
        ret = _res.content
        _res.close()
        return base64.b64encode(ret)

    @staticmethod
    def baidu_ocr(img: bytes, api_key, secret_key):
        _params = {
            "grant_type": "client_credentials",
            "client_id": api_key,
            "client_secret": secret_key
        }
        url = 'https://aip.baidubce.com/oauth/2.0/token'
        response = requests.get(url, params=_params)
        access_token = response.json().get('access_token')

        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
        _params = {
            "access_token": access_token
        }
        _data = {
            "image": img,
            "language_type": "ENG"
        }
        response = requests.post(url, params=_params, data=_data)
        res = response.json()

        if res.get('words_result_num') > 0 and len(res.get('words_result')[0].get('words')) >= 4:
            return res.get('words_result')[0].get('words')[0:4]
        else:
            return '....'

    def luogu_login(self, username: str, password: str, api_key, secret_key):
        def judge_captcha(_s: str):
            for _i in _s:
                if _i not in '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz':
                    print(f"验证码错误:{_s}")
                    return False
            return True

        _url = "https://www.luogu.com.cn/api/auth/userPassLogin"

        _data = {
            "username": username,
            "password": password,
            "captcha": self.baidu_ocr(self.get_captcha(), api_key, secret_key),
        }
        while not judge_captcha(_data["captcha"]):
            _data["captcha"] = self.baidu_ocr(self.get_captcha(), api_key, secret_key)

        res = requests.post(_url, json=_data, headers=headers)
        return res

    @staticmethod
    def sign():
        res = requests.get(
            "https://www.luogu.com.cn/index/ajax_punch", headers=headers).json()
        return res

    @staticmethod
    def parse_succ(s: str):
        return BeautifulSoup(s.replace(r"\/", '/'), 'html.parser').find('strong').text

    def main(self):
        username = self.check_item.get("username")
        password = self.check_item.get("password")
        api_key = self.check_item.get("api_key")
        secret_key = self.check_item.get("secret_key")
        try_count = self.check_item.get("try_count", 5)
        headers["cookie"], headers["x-csrf-token"] = self.get_csrf()
        msg = {
            "账号信息": "未知",
            "锁定状态": "未知",
            "签到信息": "未知",
            "错误信息": "未知"
        }
        while try_count > 0:
            try_count -= 1
            res = self.luogu_login(username, password, api_key, secret_key)
            res_json = res.json()
            if 'status' in res_json:
                print(res_json['errorMessage'], res_json['status'])
                msg.clear()
                msg["错误信息"] = res_json['errorMessage']
                continue
            else:
                print("登录成功  用户名:", res_json['username'])
                msg.clear()
                msg["账号信息"] = res_json['username']
                msg["锁定状态"] = '是' if res_json['locked'] else '否'
                headers['cookie'] = headers['cookie'].replace(
                    "_uid=0",
                    f"_uid={res.cookies.get_dict()['_uid']}")
                succ = self.sign()
                if succ['code'] == 200:
                    _ = f"已经在洛谷连续打卡了 {self.parse_succ(succ['more']['html'])} 天"
                    print(_)
                    msg["签到信息"] = _
                else:
                    print(succ['message'])
                    msg["签到信息"] = succ['message']
                return '\n'.join([f"{i}: {msg[i]}" for i in msg])


if __name__ == "__main__":
    with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.json"), "r", encoding="utf-8") as f:
        datas = json.loads(f.read())
    _check_item = datas.get("LUOGU", [])[0]
    print(Luogu(check_item=_check_item).main())
